package common

import (
	"time"

	"gitee.com/liu_deping/gin-vue/model"
	"github.com/dgrijalva/jwt-go"
)

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

var jwtKey = []byte("zhangxueiloveyou")

// 生成token
func ReleaseToken(user *model.User) (string, error) {
	expirationTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		UserId: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "oceanlearn.teach",
			Subject:   "user token",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtKey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

//eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjMsImV4cCI6MTY4Njc1NzI5NCwiaWF0IjoxNjg2MTUyNDk0LCJpc3MiOiJvY2VhbmxlYXJuLnRlYWNoIiwic3ViIjoidXNlciB0b2tlbiJ9.ATsSlHvbUF_WABGB3BuUlY7-xf2xgueDiWY5u1Oquco
//eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjMsImV4cCI6MTY4Njc1NzQ1NCwiaWF0IjoxNjg2MTUyNjU0LCJpc3MiOiJvY2VhbmxlYXJuLnRlYWNoIiwic3ViIjoidXNlciB0b2tlbiJ9.uUwmxUuL8dLIhR5Vt6hBTx_nGKCdEeP7MiwRIwwOJ8U

// 解析token
func ParesToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtKey, nil
	})

	return token, claims, err
}
